﻿using System.Text;
using System;

namespace MySqlManager
{
    /// <summary>
    /// Layer class over a MySqlCommand used to insert data to a MySQL database table
    /// </summary>
    public class MySqlInsert : SqlQuery
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MySqlInsert"/> class
        /// </summary>
        public MySqlInsert()
            : base()
        {
            this.executeDelegate = this.ExecuteNonQuery;
        }

        /// <summary>
        /// Inserts a value to the new Row
        /// </summary>
        /// <param name="value">Object that will be inserted</param>
        /// <param name="column">Name of the column where will be inserted the object</param>
        public MySqlInsert Insert(object value, string column)
        {
            this.AddParameter(column, value);
            return this;
        }

        /// <summary>
        /// Release all resources used by the MySqlInsert
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
        }

        /// <summary>
        /// Release the resources used by the MySqlInsert
        /// </summary>
        /// <param name="disposeNative">true if native objects should be disposed</param>
        private void Dispose(bool disposeNative)
        {
            if (disposeNative)
            {
                //dispose any native objects here
            }
            this.mySqlCommand.Dispose();
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Method called by the SqlQuery base methods Execute and BeginExecute
        /// </summary>
        private void ExecuteNonQuery()
        {
            StringBuilder values = new StringBuilder("(");
            StringBuilder cmd = new StringBuilder("Insert into ")
                .Append(this.tableName)
                .Append(" (");
            string column;
            while (this.parameters.Count > 0)
            {
                column = this.parameters.Dequeue();
                cmd.Append(column);
                values.Append('?')
                    .Append(column);
                if (this.parameters.Count != 0)
                {
                    cmd.Append(',');
                    values.Append(',');
                }
            }

            values.Append(')');
            cmd.Append(')')
            .Append(" Values ")
            .Append(values.ToString());
            this.AppendWhereStatments(cmd);
            cmd.Append(';');
            this.mySqlCommand.CommandText = cmd.ToString();
            using (this.mySqlCommand.Connection = MySqlCore.GetConnection())
            {
                this.mySqlCommand.ExecuteNonQuery();
            }
        }
    }
}
